package com.example.demo.controller;

import com.example.demo.entity.User;
import com.mongodb.client.result.UpdateResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/CollectionUpdateController")
@Api(tags = "集合更新管理")
public class CollectionUpdateController {
    @Autowired
    private MongoTemplate mongoTemplate;

    @GetMapping("updateFirst")
    @ApiOperation(value = "一条更新")
    public String updateFirst(){
        Update update = new Update();
        update.set("salary",444.4);
        mongoTemplate.updateFirst(Query.query(Criteria.where("name").is("string")),update,User.class);
        List<User> objects = mongoTemplate.find(Query.query(Criteria.where("name").is("string")),User.class);
        return objects.toString();
    }

    @GetMapping("updateMulti")
    @ApiOperation(value = "一条更新")
    public String updateMulti(){
        Update update = new Update();
        update.set("salary",444.4);
        mongoTemplate.updateMulti(Query.query(Criteria.where("name").is("string")),update,User.class);
        List<User> objects = mongoTemplate.find(Query.query(Criteria.where("name").is("string")),User.class);
        return objects.toString();
    }

    @GetMapping("upsert")
    @ApiOperation(value = "一条更新")
    public String upsert(){
        Update update = new Update();
        update.setOnInsert("id",10);
        update.setOnInsert("name","chenke");
        update.set("salary",444.4);
        UpdateResult updateResult = mongoTemplate.upsert(Query.query(Criteria.where("name").is("1")), update, User.class);
        List<User> objects = mongoTemplate.find(Query.query(Criteria.where("name").is("1")),User.class);
        return objects.toString();
    }
}
